package com.zzy.mccjt.gateway.system.filter;


/*import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;*/
import com.google.common.base.Charsets;
/*import com.netflix.zuul.context.RequestContext;*/
import com.zzy.mccjt.gateway.common.FilterOrders;
import com.zzy.mccjt.gateway.common.enums.AuthenError;
import com.zzy.mccjt.gateway.common.enums.GateWayPreEnum;
import com.zzy.mccjt.gateway.common.properties.AuthorizationProperties;
/*import com.zzy.mccjt.pojo.common.AdminConstants;
import com.zzy.mccjt.pojo.common.CurrentUser;
import com.zzy.mccjt.pojo.common.TokenProperties;*/
/*import com.zzy.mccjt.service.common.framework.constants.BaseHeaderConstants;
import com.zzy.mccjt.service.common.framework.error.impl.CommonError;
import com.zzy.mccjt.service.common.framework.exception.BusinessException;
import com.zzy.mccjt.service.common.framework.response.WebApiResponse;
import com.zzy.mccjt.service.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;*/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*import javax.servlet.http.HttpServletResponse;*/
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 描述：ZuulFilter
 *
 * @author likejie
 * @date 2018/3/21
 */
@Component
/*@Slf4j*/
public class SecurityFilter /*implements GlobalFilter, Ordered*/{

   /* @Autowired
    private AuthorizationProperties gatewayProperties;

    @Autowired
    private TokenProperties tokenProperties;

    @Override
    public int getOrder() {
        return FilterOrders.SECURITY_FILTER;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        HttpHeaders headers = serverHttpRequest.getHeaders();
        RequestContext ctx = RequestContext.getCurrentContext();

        String auth = headers.getFirst(HttpHeaders.AUTHORIZATION);
        log.info("auth:{}", auth);
        String token = GateWayPreEnum.getToken(GateWayPreEnum.CUSTOMER, auth);
        //token校验
        if(StringUtils.isBlank(token)){
            log.error("token is null");
            fail(CommonError.UNAUTHORIZED.getCode(), ctx,
                    CommonError.UNAUTHORIZED.getMessage());
            return null;
        }
        if (!isValidJwt(token)) {
            log.error("token is invalid");
            fail(CommonError.UNAUTHORIZED.getCode(), ctx,
                    CommonError.UNAUTHORIZED.getMessage());
            return null;
        }
        *//*if(!menuValidate(exchange,token)){
            log.info("菜单校验不通过");
            return unauthorized(serverHttpResponse);
        }*//*
        if(!dataValidate(exchange)){
            log.info("数据权限校验不通过");
            fail(CommonError.UNAUTHORIZED.getCode(), ctx,
                    CommonError.UNAUTHORIZED.getMessage());
            return null;
        }

        String[] headerValues = new String[]{token};
        ServerHttpRequest newRequest = exchange.getRequest().mutate().header(BaseHeaderConstants.REQUEST_HEADER_AUTH, headerValues).build();
        //构建新的ServerWebExchange实例
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        return chain.filter(newExchange);
    }



    public static Mono<Void> unauthorized(ServerHttpResponse var0) {
        var0.setStatusCode(HttpStatus.UNAUTHORIZED);
        String var1 = JSON.toJSONString(WebApiResponse.error(AuthenError.INTERFACE_NO_AUTH));
        byte[] var2 = var1.getBytes(StandardCharsets.UTF_8);
        DataBuffer var3 = var0.bufferFactory().wrap(var2);
        return Mono.defer(() -> {
            return var0.writeWith(Mono.just(var3));
        });
    }
    *//**
     * TOKEN 校验
     *//*
    private boolean isValidJwt(String token) {
        TokenProperties.JwtProperties jwtProperties=tokenProperties.getCustomer();
        if(jwtProperties==null){
            throw  new BusinessException("config error: tokenProperties is null ");
        }
        //校验token
        return JwtUtil.parseJWT(jwtProperties.getIssuer(),token,jwtProperties.getBase64Security())!=null;
    }

    *//**
     * TOKEN 校验
     *//*
    private CurrentUser getUser(String token) {
        CurrentUser user = new CurrentUser(AdminConstants.USER_ID, AdminConstants.USER_LOGIN_NAME,
                AdminConstants.USER_NAME);
        TokenProperties.JwtProperties jwtProperties=tokenProperties.getCustomer();
        if(jwtProperties==null){
            throw  new BusinessException("config error: tokenProperties is null ");
        }
        //校验token
        Claims claims=JwtUtil.parseJWT(jwtProperties.getIssuer(),token,jwtProperties.getBase64Security());
        if(claims!=null){
            user = JSONObject.parseObject(claims.getSubject(), CurrentUser.class);
        }
        return user;
    }
    *//**
     * 白名单校验
     *//*
    private boolean isWhitelist(ServerHttpRequest request) {

        boolean result = false;
        String path = request.getPath().toString();
        HttpMethod httpMethod = request.getMethod();
        if (httpMethod != null && httpMethod.name().equals(HttpMethod.OPTIONS.name())) {
            result = true;
        } else if (StringUtils.isNotBlank(path)) {
            List<String> urls = gatewayProperties.getWhitelist();
            for (String url : urls) {
                if (path.contains(url)) {
                    result = true;
                    break;
                }
            }
        }
        log.debug("path:{}, whitelist:{}", path,result);
        return result;

    }
    *//**
     * 数据权限校验
     *//*
    private boolean dataValidate(ServerWebExchange exchange){
        *//*if(RedisKey.GATEWAY_DATA_KEY.getVal() == null){
            return false;
        }*//*
        return true;
    }

    *//**
     * 返回逻辑统一处理
     *//*
    private void fail(int errorCode, RequestContext ctx, String message) {
        HttpServletResponse response = ctx.getResponse();
        // 设置字符集
        response.setCharacterEncoding(Charsets.UTF_8.name());
        // 设置相应格式
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        ctx.setResponse(response);
        // 过滤该请求，不往下级服务去转发请求，到此结束
        ctx.setSendZuulResponse(false);
        WebApiResponse rsp = WebApiResponse.error(errorCode, message);
        ctx.setResponseBody(JSONObject.toJSONString(rsp));
    }
*/
}